#!/usr/bin/env python
# -*- coding: utf-8 -*-
##
#  Project: Kelindo - Unsupervised Music Organizer  
#  Author: Nicola Bicocchi <nicola.bicocchi@gmail.com>, Nicolo' Torreggiani <nicolo.torreggiani@gmail.com>, Gianluca Puglia <gianluca.puglia@gmail.com>, Matteo Senardi <pualien@gmail.com>
#  Copyright: 2013 Nicola Bicocchi, Nicolo' Torreggiani, Gianluca Puglia, Matteo Senardi
#  License: GPL-2+
#  This program is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by the Free
#  Software Foundation; either version 2 of the License, or (at your option)
#  any later version.
# 
#  This program is distributed in the hope that it will be useful, but WITHOUT
#  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
#  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
#  more details.
# 
# On Debian GNU/Linux systems, the full text of the GNU General Public License
# can be found in the file /usr/share/common-licenses/GPL-2.
##

from kelindo.const import MinVersions, Version
from kelindo.qltk.window import Window

def _python_init():
    import re, sys
    if sys.version_info < MinVersions.PYTHON:
        actual = Version(sys.version_info[:3])
        print("Python %s required. %s found." % (MinVersions.PYTHON, actual))

    # The default regex escaping function doesn't work for non-ASCII.
    # Use a blacklist of regex-specific characters instead.
    def re_esc(str, BAD="/.^$*+?{,\\[]|()<>#=!:"):
        needs_escape = lambda c: (c in BAD and "\\" + c) or c
        return "".join(map(needs_escape, str))
    re.escape = re_esc
    return


def _gtk_init(icon_name=None):
    import pygtk
    pygtk.require('2.0')
    import gtk
    import gobject
    gobject.threads_init()

    pygtk_ver = Version(gtk.pygtk_version)
    if pygtk_ver < MinVersions.PYGTK:
        print("PyGTK %s required. %s found." % (MinVersions.PYGTK, pygtk_ver))

    if icon_name:
        gtk.window_set_default_icon_from_file(icon_name)
    return


def set_process_title(title):
    """Sets process name as visible in ps or top. Requires ctypes libc
    and is almost certainly *nix-only. See issue 736"""

    import os
    if os.name == "nt":
        return

    try:
        import ctypes
        libc = ctypes.CDLL('libc.so.6')
        # 15 = PR_SET_NAME, apparently
        libc.prctl(15, title, 0, 0, 0)
    except:
        print("Couldn't find module libc.so.6 (ctypes).")


def _init_signal(title, icon_name):
    _python_init()
    _gtk_init(icon_name)

    import gobject
    gobject.set_prgname(title)
    set_process_title(title)
    gobject.idle_add(set_process_title, title)
    gobject.set_application_name(title)
        
    import gtk
    Window()
    gtk.main()
